package com.supermap.qdsearch.fragment;


import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.supermap.android.maps.CoordinateReferenceSystem;
import com.supermap.android.maps.DefaultItemizedOverlay;
import com.supermap.android.maps.LayerView;
import com.supermap.android.maps.MapController;
import com.supermap.android.maps.MapView;
import com.supermap.android.maps.Overlay;
import com.supermap.android.maps.OverlayItem;
import com.supermap.android.maps.Point2D;
import com.supermap.qdsearch.R;
import com.supermap.qdsearch.app.SearchApp;
import com.supermap.qdsearch.entity.MapEntity;
import com.supermap.qdsearch.utils.LocationService;
import com.supermap.qdsearch.utils.LocationUtils;
import com.supermap.qdsearch.utils.NetUtils;
import com.supermap.qdsearch.utils.ToastUtils;
import com.supermap.qdsearch.widget.CustomProgressBar;
import com.yanzhenjie.nohttp.rest.Response;
import com.yanzhenjie.nohttp.rest.StringRequest;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * A simple {@link Fragment} subclass.
 */
public class LocationFragment extends Fragment {

    @BindView(R.id.map_view)
    MapView mapView;
    Unbinder unbinder;
    @BindView(R.id.btn_location)
    Button btnLocation;
    @BindView(R.id.spinner)
    Spinner spinner;

    private String getMapsUrl;
    private List<MapEntity> list;

    //    private String rest = "http://117.159.25.210:8090/iserver/services/map-SDDY/rest/maps/土地利用";
    private String rest;
    private String base;
    private CoordinateReferenceSystem crs;

    private LocationService locationService;
    private CustomProgressBar dialog;


    // 触屏的x坐标
    private int touchX;
    // 触屏的y坐标
    private int touchY;
    //坐标
    private Point2D longTouchGeoPoint = null;

    private DefaultItemizedOverlay blueMarkerOverlay = null;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_location, container, false);
        unbinder = ButterKnife.bind(this, view);

        list = new ArrayList<>();
        getMapsUrl = getResources().getString(R.string.get_maps_url);
        rest = getResources().getString(R.string.map_rest_url);
        base = getResources().getString(R.string.map_base_url);

        dialog = new CustomProgressBar(getContext());
        dialog.show();

        initMap();
        initSpnnner();


        locationService = ((SearchApp) ((getActivity()).getApplication())).locationService;
        locationService.stop();

        return view;
    }

    private void startLocation() {
        // -----------location config ------------
        //获取locationservice实例，建议应用中只初始化1个location实例，然后使用，可以参考其他示例的activity，都是通过此种方式获取locationservice实例的
        locationService.registerListener(mListener);
        //注册监听
        locationService.setLocationOption(locationService.getDefaultLocationClientOption());
        locationService.start();
    }


    /**
     * 初始化地图
     */
    private void initMap() {
        crs = new CoordinateReferenceSystem();
        crs.wkid = 4326;
        addFristLayer();

        Drawable drawableBlue = getResources().getDrawable(R.mipmap.blue_pin);
        blueMarkerOverlay = new DefaultItemizedOverlay(drawableBlue);
        TouchOverlay touchOverlay = new TouchOverlay();
        mapView.getOverlays().add(touchOverlay);
        mapView.getOverlays().add(blueMarkerOverlay);
        mapView.addMapViewEventListener(new MapView.MapViewEventListener() {
            @Override
            public void moveStart(MapView mapView) {

            }

            @Override
            public void move(MapView mapView) {

            }

            @Override
            public void moveEnd(MapView mapView) {

            }

            @Override
            public void touch(MapView mapView) {

            }

            @Override
            public void longTouch(MapView mapView) {
                if (longTouchGeoPoint != null) {
                    addOverlay();
                    ToastUtils.showShortToast(longTouchGeoPoint.getX()+","+longTouchGeoPoint.getY());
                }
            }

            @Override
            public void zoomStart(MapView mapView) {

            }

            @Override
            public void zoomEnd(MapView mapView) {

            }

            @Override
            public void mapLoaded(MapView mapView) {

            }
        });



    }


    public void initSpnnner() {
        StringRequest request = new StringRequest(getMapsUrl);
        MapEntity mapEntity = new MapEntity("天地图", rest);
        list.add(mapEntity);
        new NetUtils<Object>(request) {
            @Override
            public Object onSuccess(Response<String> response) {


                String s = response.get();
                JSONArray jsonArray = JSON.parseArray(s);
                int size = jsonArray.size();
                for (int i = 0; i < size; i++) {
                    JSONObject object = jsonArray.getJSONObject(i);
                    String name = object.getString("name");
                    String path = object.getString("path");
                    MapEntity mapEntity = new MapEntity(name, path);
                    if (!"天地图".equals(name)) {
                        list.add(mapEntity);
                    }
                }
                spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                    boolean isFirst = true;

                    @Override
                    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                        MapEntity mapEntity = (MapEntity) spinner.getSelectedItem();
                        String name = mapEntity.getName();
                        String path = mapEntity.getPath();
                        if (list.get(0).getName().equals(name) && isFirst) {
                            isFirst = false;
                            return;
                        }

                        if ("天地图".equals(name)) {
                            rest = path;
                            addFristLayer();
                        } else {
                            rest = base + name;
                            addOhterLayer();
                        }
                    }

                    @Override
                    public void onNothingSelected(AdapterView<?> parent) {

                    }
                });
                spinner.setAdapter(new ArrayAdapter<MapEntity>(getContext(), android.R.layout.simple_spinner_item, list));
                dialog.dismiss();
                return null;
            }

            @Override
            public Object onFail(Response<String> response) {
                ToastUtils.showShortToast("请检查网络~");
                return null;
            }
        };
    }

    public void addFristLayer() {
        mapView.removeAllLayers();
        LayerView restView = new LayerView(getContext());
        restView.setURL(rest);
        restView.setCRS(crs);
        mapView.addLayer(restView);
        Point2D point2D = new Point2D(118.603243, 37.775859);
        MapController controller = mapView.getController();
        controller.setCenter(point2D);
        controller.setZoom(4);
        //启用内置的缩放控件
        mapView.setBuiltInZoomControls(true);
        mapView.setClickable(true);
        mapView.invalidate();
    }

    public void addOhterLayer() {
        mapView.removeAllLayers();
        LayerView restView = new LayerView(getContext());
        restView.setURL(rest);
        restView.setCRS(crs);
        mapView.addLayer(restView);
        Point2D point2D = new Point2D(118.603243, 37.775859);
        MapController controller = mapView.getController();
        controller.setCenter(point2D);
        controller.setZoom(0);
        //启用内置的缩放控件
        mapView.setBuiltInZoomControls(true);
        mapView.setClickable(true);
        mapView.invalidate();
    }

    /**
     * 画出GPS图标
     */
    public void drawGps(BDLocation location) {

        double x = location.getLongitude();
        double y = location.getLatitude();
        Drawable drawableBlue = getResources().getDrawable(R.mipmap.location_checked);
        DefaultItemizedOverlay overlay = new DefaultItemizedOverlay(drawableBlue);
//        OverlayItem overlayItem2 = new OverlayItem(new Point2D(118.603243, 37.775859), "", "");
        OverlayItem overlayItem2 = new OverlayItem(new Point2D(x, y), "", "");
        overlay.addItem(overlayItem2);
        mapView.getOverlays().add(overlay);
        Point2D point2D = new Point2D(x, y);
        MapController controller = mapView.getController();
        controller.setCenter(point2D);
        controller.setZoom(10);
        // 重新onDraw一次
        mapView.invalidate();
    }


    //定义一个更新显示的方法
    private void updateShow(BDLocation location) {
        drawGps(location);
        String addrStr = location.getAddrStr();
        ToastUtils.showShortToast(addrStr);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (locationService != null) {
            locationService.unregisterListener(mListener);
            locationService.stop();
        }
        unbinder.unbind();
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {

    }


    @OnClick({R.id.btn_location})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_location:
                if (!LocationUtils.isGpsEnabled()) {
                    ToastUtils.showShortToast("请打开GPS~");
                    LocationUtils.openGpsSettings();
                } else {
                    startLocation();
                }
                break;
        }
    }


    /*****
     *
     * 定位结果回调，重写onReceiveLocation方法，可以直接拷贝如下代码到自己工程中修改
     *
     */
    private BDAbstractLocationListener mListener = new BDAbstractLocationListener() {

        @Override
        public void onReceiveLocation(BDLocation location) {
            // TODO Auto-generated method stub
            if (null != location && location.getLocType() != BDLocation.TypeServerError) {

                updateShow(location);
            }
        }

    };


    /**
     * 增加Overlay，刷新地图
     */
    public void addOverlay() {
        if (longTouchGeoPoint != null) {
            OverlayItem overlayItem = new OverlayItem(longTouchGeoPoint, "", "");
            mapView.getOverlays().add(blueMarkerOverlay);
            blueMarkerOverlay.addItem(overlayItem);
        }
        mapView.invalidate();
    }


    /**
     * 触屏Overlay
     */
    class TouchOverlay extends Overlay {
        @Override
        public boolean onTouchEvent(MotionEvent event, final MapView mapView) {
            touchX = Math.round(event.getX());
            touchY = Math.round(event.getY());
            // 记录点击位置
            longTouchGeoPoint = mapView.getProjection().fromPixels(touchX, touchY);
            return false;
        }
    }
}
